<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Movie extends MY_Controller{

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/home
	 *	- or -  
	 * 		http://example.com/index.php/home/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
    function __construct()
    {
        parent::__construct();
		
		//Google Analytics ID
		$this->data['ga_id'] = 15;		
		
		//Load model
		$this->load->model('movie_model');
				
		//Load Video Script
		$this->data['js'][] = "movieScript.js";
		$this->data['css'][] = "movieStyle.css";
		
		 //Load Library
  		$this->load->library('pagination');
		
		//Set SEO Tag
		$this->data['seo_title'] = 'ดูหนัง หนังเข้าใหม่ หนังไทย หนังต่างประเทศ เพลงประกอบภาพยนต์ | You2Play.com';
		$this->data['seo_description'] = 'ดูหนัง หนังเข้าใหม่ หนังไทย หนังต่างประเทศ เพลงประกอบภาพยนต์ ข่าวในวงการภาพยนต์ คลิปวีดีโอ';
		$this->data['seo_keyword'] = 'ดูหนัง, หนังเข้าใหม่, หนังไทย, หนังต่างประเทศ, เพลงประกอบภาพยนต์';			
    }
	
	private function movie_header()
	{
		return $this->load->view($this->router->class."/header", $this->data,TRUE);
	}
	
	/*Home*/	 
	public function index()
	{
		//Load Javascript
		$this->data['js'][] = "jquery.multipleelements.cycle.min.js";		
			
		//Load Module
		$this->data['module'] = $this->module('movie');

		/*Hilight*/
		$this->data['dataMovieHilight'] = json_decode($this->db->get_where('module_page',array('page' => 'movie'),1)->row()->json);

		//Showing
		if ( !$this->data['movieShowing'] = $this->memcache->get('dataMovieShow')):
			$this->data['movieShowing'] = $this->db->select('t.movie_id,t.views,j.movie_name,DATE(t.movie_publish_date) as movie_publish_date')->
			join('movie_info as j',"t.movie_id=j.movie_id AND t.is_video_clip='0' AND t.is_publish='1'",'INNER')->
			where('DATE(t.movie_publish_date) <= CURDATE()')->
			order_by('t.movie_publish_date','DESC')->
			get('movie as t',8)->
			result();
			foreach($this->data['movieShowing'] as $value):
				$dataImage = $this->db->select('t.movie_file_name,t.movie_file_ext')->
				join('movie as j',"j.movie_id=t.movie_id AND t.movie_image_order=0",'INNER')->
				get_where('movie_image as t',array('t.movie_id' => $value->movie_id),1)->
				row();
					$value->movie_file_name = @$dataImage->movie_file_name;
					$value->movie_file_ext = @$dataImage->movie_file_ext;
			endforeach;
			$this->memcache->set('dataMovieShow', $this->data['movieShowing'], $this->memcache_time);
		endif;
		
		//Hit
		if ( !$this->data['movieHit'] = $this->memcache->get('dataMovieHit')):
			$this->data['movieHit'] = $this->db->select('t.movie_id,t.views,j.movie_name,DATE(t.movie_publish_date) as movie_publish_date')->
			join('movie_info as j',"t.movie_id=j.movie_id",'INNER')->
			order_by('t.views','DESC')->
			get_where('movie as t',"t.is_video_clip = '0' AND t.is_publish = '1' AND DATE(t.movie_publish_date) <= CURDATE() AND DATE(t.movie_publish_date) >= DATE_SUB(CURDATE(),INTERVAL 14 DAY)",4)->
			result();
			foreach($this->data['movieHit'] as $value):
				$dataImage = $this->db->select('t.movie_file_name,t.movie_file_ext')->
				join('movie as j',"j.movie_id=t.movie_id AND t.movie_image_order=0",'INNER')->
				get_where('movie_image as t',array('t.movie_id' => $value->movie_id),1)->
				row();
					$value->movie_file_name = @$dataImage->movie_file_name;
					$value->movie_file_ext = @$dataImage->movie_file_ext;
				$dataView = $this->db->select('t.movie_click_views')->
				join('movie as j',"j.movie_id=t.movie_id",'INNER')->
				get_where('movie_click_stat as t',array('t.movie_id' => $value->movie_id),1)->
				row();
					$value->movie_click_views = @$dataView->movie_click_views;
			endforeach;
			$this->memcache->set('dataMovieHit', $this->data['movieHit'], $this->memcache_time);
		endif;
		
		//Clip
		if ( !$this->data['movieClip'] = $this->memcache->get('dataMovieClip')):
			$this->data['movieClip'] = $this->db->select('t.movie_id,t.views,t.create_date,j.movie_name')->
			join('movie_info as j',"t.movie_id=j.movie_id AND t.is_video_clip='1' AND t.is_publish='1'",'INNER')->
			order_by('t.movie_id DESC')->
			get('movie as t',5)->
			result();
			foreach($this->data['movieClip'] as $value):
				$dataImage = $this->db->select('t.movie_file_name,t.movie_file_ext')->
				join('movie as j',"j.movie_id=t.movie_id AND t.movie_image_order=0",'INNER')->
				get_where('movie_image as t',array('t.movie_id' => $value->movie_id),1)->
				row();
					$value->movie_file_name = @$dataImage->movie_file_name;
					$value->movie_file_ext = @$dataImage->movie_file_ext;
			endforeach;
			$this->memcache->set('dataMovieClip', $this->data['movieClip'], $this->memcache_time);
		endif;
		
		//Coming Soon
		if ( !$this->data['movieComingSoon'] = $this->memcache->get('dataMovieComingSoon')):
			$this->data['movieComingSoon'] = $this->db->select('t.movie_id,t.views,j.movie_name,DATE(t.movie_publish_date) as movie_publish_date')->
			join('movie_info as j',"t.movie_id=j.movie_id AND t.is_video_clip='0' AND t.is_publish='1'",'INNER')->
			where('DATE(t.movie_publish_date) > CURDATE()')->
			order_by('t.movie_publish_date','ASC')->
			get('movie as t',16)->
			result();
			foreach($this->data['movieComingSoon'] as $value):
				$dataImage = $this->db->select('t.movie_file_name,t.movie_file_ext')->
				join('movie as j',"j.movie_id=t.movie_id AND t.movie_image_order=0",'INNER')->
				get_where('movie_image as t',array('t.movie_id' => $value->movie_id),1)->
				row();
					$value->movie_file_name = @$dataImage->movie_file_name;
					$value->movie_file_ext = @$dataImage->movie_file_ext;
			endforeach;
			$this->memcache->set('dataMovieComingSoon', $this->data['movieComingSoon'], $this->memcache_time);
		endif;
				
		$this->data['content'] = $this->router->class."/index";
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);
		
	}
	
	private function ajax_movie_pager($selection = NULL)
	{	
		echo $this->movie_pager($selection);
		exit;
	}
	
	private function movie_pager($selection = NULL)
	{
		switch($selection):
			case "showing":
				$this->data['module_type'] = 'showing';
				$this->data['title'] = "หนังใหม่ชนโรง";
				$this->data['image_folder'] = 'movie';
				$this->data['image_demension'] = '120x175';		
				$searchCondition = "DATE(t.movie_publish_date) <= CURDATE() AND t.is_video_clip='0' AND t.is_publish='1'";
				$orderBy = "t.movie_publish_date DESC";	
			break;
			case "coming_soon":
				$this->data['module_type'] = 'coming_soon';
				$this->data['title'] = "โปรแกรมหน้า";
				$this->data['image_folder'] = 'movie';
				$this->data['image_demension'] = '120x175';					
				$searchCondition = "DATE(t.movie_publish_date) > CURDATE() AND t.is_video_clip = '0' AND t.is_publish = '1'";
				$orderBy = "t.movie_publish_date ASC";			
			break;
			case "hit":
				$this->data['module_type'] = 'hit';
				$this->data['title'] = "หนังฮิตในรอบสัปดาห์";
				$this->data['image_folder'] = 'movie';
				$this->data['image_demension'] = '120x175';
				$searchCondition = "DATE(t.movie_publish_date) <= CURDATE() AND DATE(t.movie_publish_date) >= DATE_SUB(CURDATE(),INTERVAL 7 DAY) AND t.is_video_clip = '0' AND t.is_publish = '1'";
				$orderBy = "t.views DESC";				
			break;
			case "clip":
				$this->data['module_type'] = 'clip';
				$this->data['title'] = "คลิปวีดีโอ";
				$this->data['image_folder'] = 'movie';
				$this->data['image_demension'] = '120x80';
				$searchCondition = "t.is_video_clip = '1' AND t.is_publish = '1'";
				$orderBy = "t.movie_id DESC";			
			break;
			case "music":
				$this->data['module_type'] = 'music';
				$this->data['title'] = "เพลงประกอบภาพยนตร์";
				$this->data['image_folder'] = 'album';
				$this->data['image_demension'] = '140x140';
				$searchCondition = "t.is_show_ost_song_mood = '1' AND t.is_publish = '1'";
				$orderBy = "t.song_id DESC";					
			break;
			case "news":
				$this->data['module_type'] = 'news';
				$this->data['title'] = "ข่าววงการภาพยนตร์";
				$this->data['image_folder'] = 'news';
				$this->data['image_demension'] = '120x80';
				$searchCondition = "t.news_type_id = 6 AND t.is_publish = '1'";	
				$orderBy = "t.news_id DESC";		
			break;
			default:
				$this->page_missing();
		endswitch;
		
		if($selection == "music"):
			$config['base_url'] = current_url().'?'.query_string(array('p'));
			$config['total_rows'] = $this->db->from('song as t')
			->join('song_info as j','j.song_id=t.song_id','INNER')
			->where($searchCondition)
			->count_all_results();
			$config['per_page'] = 20;
			$config['num_links'] = 5;
			$config['first_link'] = '<span class="arrows first ">&laquo;</span>';
			 $config['next_link'] = '<span class="arrows next ">&gt;</span>';
			$config['prev_link'] = '<span class="arrows prev ">&lt;</span>';
			$config['last_link'] = '<span class="arrows last ">&raquo;</span>';
			$config['page_query_string'] = TRUE;
			$config['query_string_segment'] = 'p';
			$this->pagination->initialize($config);
			$this->data['pager'] = $this->pagination->create_links();
				
			$this->data['dataMovie'] = $this->db->select('t.song_id as id,t.views,j.song_name as name,DATE(t.create_date) as date')
			->join('song_info as j',"t.song_id=j.song_id",'INNER')
			->order_by($orderBy)
			->get_where('song as t',$searchCondition,$config['per_page'],intval($this->input->get('p')))
			->result();
			foreach($this->data['dataMovie'] as $value):
				$value->image = $this->db->select('album_file_name as image_file_name,album_file_ext as image_file_ext')
				->join('album_info as j','j.album_id=t.album_id','INNER')
				->get_where('song_album as t',array('t.song_id' => $value->id),1)->row();
			endforeach;		
		elseif($selection == "news"):			
			$config['base_url'] = current_url().'?'.query_string(array('p'));
			$config['total_rows'] = $this->db->from('news as t')
			->where($searchCondition)
			->count_all_results();
			$config['per_page'] = 36;
			$config['num_links'] = 5;
			$config['first_link'] = '<span class="arrows first ">&laquo;</span>';
		 	$config['next_link'] = '<span class="arrows next ">&gt;</span>';
		  	$config['prev_link'] = '<span class="arrows prev ">&lt;</span>';
			$config['last_link'] = '<span class="arrows last ">&raquo;</span>';
			$config['page_query_string'] = TRUE;
			$config['query_string_segment'] = 'p';
			$this->pagination->initialize($config);
			$this->data['pager'] = $this->pagination->create_links();
				
			$this->data['dataMovie'] = $this->db->select('t.news_id as id,j.news_subject as name,t.news_publish_date as date,t.views')
			->join('news_info as j',"j.news_id=t.news_id",'INNER')
			->order_by($orderBy)
			->get_where('news as t',$searchCondition,$config['per_page'],intval($this->input->get('p')))
			->result();
			foreach($this->data['dataMovie'] as $value):
				$value->image = $this->db->select('news_file_name as image_file_name,news_file_ext as image_file_ext')
				->order_by('news_image_order ASC,news_image_id ASC')
				->get_where('news_image',array('news_id' => $value->id),1)->row();
			endforeach;
		else:
			$config['base_url'] = current_url().'?'.query_string(array('p'));
			$config['total_rows'] = $this->db->from('movie as t')
			->join('movie_info as j','j.movie_id=t.movie_id','INNER')
			->where($searchCondition)
			->count_all_results();
			$config['per_page'] = 20;
			$config['num_links'] = 5;
			$config['first_link'] = '<span class="arrows first ">&laquo;</span>';
			 $config['next_link'] = '<span class="arrows next ">&gt;</span>';
			$config['prev_link'] = '<span class="arrows prev ">&lt;</span>';
			$config['last_link'] = '<span class="arrows last ">&raquo;</span>';
			$config['page_query_string'] = TRUE;
			$config['query_string_segment'] = 'p';
			$this->pagination->initialize($config);
			$this->data['pager'] = $this->pagination->create_links();
				
			$this->data['dataMovie'] = $this->db->select('t.movie_id as id,t.views,j.movie_name as name,DATE('.($selection == "clip" ? 't.create_date':'t.movie_publish_date').') as date')
			->join('movie_info as j',"t.movie_id=j.movie_id",'INNER')
			->order_by($orderBy)
			->get_where('movie as t',$searchCondition,$config['per_page'],intval($this->input->get('p')))
			->result();
			foreach($this->data['dataMovie'] as $value):
				$value->image = $this->db->select('movie_file_name as image_file_name,movie_file_ext as image_file_ext')
				->order_by('movie_image_order ASC,movie_image_id ASC')
				->get_where('movie_image',array('movie_id' => $value->id),1)->row();
			endforeach;			
		endif;

		return $this->load->view("movie/ajax_movie",$this->data,true);
	}
	
	public function showing(){$this->category();}
	public function coming_soon(){$this->category();}
	public function hit(){$this->category();}
	public function clip(){$this->category();}
	public function music(){$this->category();}
	public function news($id = NULL){$this->category($id = NULL);}
	public function category($id = NULL)
	{
		if(!empty($id) && $this->router->method == "news"):
			$this->news_info($id);
		else:
			if($this->input->post('ajax')) $this->ajax_movie_pager($this->router->method);
			$this->data['module'] = $this->module('movie');
			$this->data['dataMovie'] = $this->movie_pager($this->router->method);
			$this->data['content'] = $this->router->class."/category";
			$this->load->view("templates/".$this->folder_templates."templates", $this->data);		
		endif;	
	}
	
	private function news_info($id)
	{
		$is_exist = $this->db->from('news')->where(array('news_id' => $id))->count_all_results();
		if(empty($is_exist)) $this->page_missing();

		//Load ColorBox
		$this->data['js'][] = "jquery.colorbox-min.js";	
		$this->data['css'][] = "colorbox.css";
				
		//Load Module
		$this->data['module'] = $this->module('movie');
		$this->data['module_facebook_plugins_share'] = $this->module_facebook_plugins_share();
		$this->data['module_facebook_plugins_comment'] = $this->module_facebook_plugins_comment(NULL,'dark');
		
		$this->data['movie_header'] = $this->movie_header();
		$this->data['dataResult'] = $this->db->get_where('news_info',array('news_id' => $id),1)->row();
		$this->data['dataResult']->image = $this->db->order_by('news_image_order','ASC')->get_where('news_image',array('news_id' => $id))->result();
		
		$this->data['content'] = $this->router->class."/news";
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);
	}
	
	public function play($id = NULL,$seo_text = NULL)
	{						
		$is_exist = $this->db->from('movie')->where(array('movie_id' => $id,'is_publish' => '1'))->count_all_results();
		if(empty($is_exist)) $this->page_missing();
		
		//Rediect if no seo text
		if(empty($seo_text)):
			$dataResult = $this->db->get_where('movie_info',array('movie_id' => $id),1)->row();
			redirect($movie_url.'play/'.intval($id).'-'.seo_url($dataResult->movie_name), 'location', 301);
		endif;			
		
		//Load Media Player
		if($this->agent->is_mobile()):
			$this->data['js'][] = "media/player.js";
		else:
			$this->data['js'][] = "media/jwplayerx.js";
		endif;	
				
		//Load ColorBox
		$this->data['js'][] = "jquery.colorbox-min.js";	
		$this->data['css'][] = "colorbox.css";
		
		//Load ZaroClipboard
		$this->data['js'][] = "ZeroClipboard/ZeroClipboard.js";	
						
		//Load Module
		$this->data['module'] = $this->module('movie');
		$this->data['module_facebook_plugins_share'] = $this->module_facebook_plugins_share(NULL,'dark');
		$this->data['module_facebook_plugins_comment'] = $this->module_facebook_plugins_comment(NULL,'dark');
		
		//Load Ads
/*		$this->data['dataAds'] = array();
		$dataAds = $this->db->select('ads_id,ads_vast,ads_weight,limit_per_day')
		->get_where('ads',"start_date <= '".date('Y-m-d H:i:s')."' AND end_date > '".date('Y-m-d H:i:s')."' AND (ads_impression = 0 OR ads_impression > views) AND is_movie = '1'")
		->result();
		foreach($dataAds as $key => $value):
			if(!empty($value->limit_per_day)):
				$impression_today = intval($this->db->select('SUM(views) as Views')
				->get_where('ads_static',"ads_id = ".$value->ads_id." AND event = 'Impression' AND DATE(date) = '".date('Y-m-d')."'")->row()->Views);
				if($impression_today < $value->limit_per_day):
					$this->data['dataAds'][] = $value;
				endif;			
			else:
				$this->data['dataAds'][] = $value;
			endif;
		endforeach;	*/
		
		//UPDATE Video (View)
		$this->db->set('views', 'views + 1', FALSE);
		$this->db->where(array('movie_id' => $id));
		$this->db->update('movie');
		
		//Keep Stat View
		$datetime = date('Y-m-d');
		$is_exist = $this->db->from('movie_click_stat')->where(array('movie_id' => $id,'update_date' => $datetime))->count_all_results();
		if(!empty($is_exist)):
			$this->db->set('movie_click_views', 'movie_click_views + 1', FALSE);
			$this->db->where(array('movie_id' => $id,'update_date' => $datetime));
			$this->db->update('movie_click_stat');
		else:
			$data = array(
				'movie_id' => $id,
				'movie_click_views' => 1,
				'update_date' => $datetime
			);
			$this->db->insert('movie_click_stat',$data);
		endif;
		
		$this->data['movie_header'] = $this->movie_header();
		$this->data['dataResult'] = $this->db->select('t.views,t.is_video_clip,t.create_date,DATE(t.movie_publish_date) as movie_publish_date,j.*')
		->join('movie_info as j','j.movie_id=t.movie_id','INNER')
		->get_where('movie as t',array('t.movie_id' => $id),1)
		->row();	
		
		$this->data['dataResult']->image = $this->db->order_by('movie_image_order','ASC')->get_where('movie_image',array('movie_id' => $id))->result();
		$this->data['dataResult']->type = $this->db->select('j.movie_type_name')
		->join('movie_type as j','j.movie_type_id=t.movie_type_id','INNER')
		->get_where('movie_type_relate as t',array('movie_id' => $id))
		->result();
		
		//Set SEO Tag
		$this->data['seo_title'] = $this->data['dataResult']->movie_name.' | ดูหนัง คลิปวีดีโอ You2Play.com';
		$this->data['seo_description'] = ''.$this->data['dataResult']->movie_name.' '.$this->data['seo_description'];
		if(!empty($this->data['dataResult']->movie_tag) && preg_match('/ดูหนัง/',$this->data['dataResult']->movie_tag)):
			$this->data['seo_keyword'] = $this->data['dataResult']->movie_tag;
		else:
			$this->data['seo_keyword'] = ($this->data['dataResult']->movie_tag ? $this->data['dataResult']->movie_tag.', ':'').'ดูหนัง';
		endif;	
			
		$this->data['fb_title'] = $this->data['seo_title'];
		if(!empty($this->data['dataResult']->image)) $this->data['fb_image'] = image_asset_url('../uploads/movie/images/120x120/'.$this->data['dataResult']->image{0}->movie_file_name.'.'.$this->data['dataResult']->image{0}->movie_file_ext);
		if(!empty($this->data['dataResult']->movie_embed)):
			if(preg_match('/\/embed\/(.+?)\"/',$this->data['dataResult']->movie_embed,$matches)):
				$this->data['fb_media'] = 'http://www.youtube.com/v/'.$matches[1].'?version=3&amp;autohide=1';
			endif;			
		else:
			$image_file = "";
			if(!empty($this->data['dataResult']->image)) $image_file = image_asset_url('../uploads/movie/images/original/'.$this->data['dataResult']->image{0}->movie_file_name.'.'.$this->data['dataResult']->image{0}->movie_file_ext);
			$media_file = other_asset_url('uploads/movie/files/'.date('Y/m/d',strtotime($this->data['dataResult']->create_date)).'/'.$this->data['dataResult']->movie_file_name1.'.'.$this->data['dataResult']->movie_file_ext1);
			$this->data['fb_media'] = 'http://static.you2play.com/2013/assets/js/media/player.swf?file='.$media_file.'&image='.$image_file.'&autostart=true';
		endif;
		$this->data['fb_type'] = 'video.movie';
		
		//GA Events
		$this->data['ga_event'] = 'CI-'.$id.'-'.seo_url($this->data['dataResult']->movie_name);		
		
		$this->data['content'] = $this->router->class."/".$this->router->method;
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);
	}
	
	/*Ajax Copy Stat*/
	public function ajax_copy_stat()
	{
		$this->movie_model->ajax_copy_stat();
	}	
}


/* End of file video.php */
/* Location: ./application/controllers/video.php */